package com.laoxu.test.rbacdemo.controller;


import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.laoxu.test.rbacdemo.common.PageRequest;
import com.laoxu.test.rbacdemo.common.Result;
import com.laoxu.test.rbacdemo.exception.AppException;
import com.laoxu.test.rbacdemo.model.SysDept;
import com.laoxu.test.rbacdemo.service.SysDeptService;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  部门控制器
 * </p>
 *
 * @author laoxu
 * @since 2020-08-09
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/api/dept")
public class SysDeptController {
    private String message;

    @Autowired
    private SysDeptService deptService;

    @GetMapping("/list")
    public Map<String, Object> deptList(PageRequest request, SysDept dept) {
        return this.deptService.findDepts(request, dept);
    }

    @PostMapping("/add")
    @RequiresPermissions("dept:add")
    public Result addDept(@RequestBody @Valid SysDept dept) throws AppException {
        try {
            this.deptService.createDept(dept);
            return Result.ok("新增部门成功");
        } catch (Exception e) {
            message = "新增部门失败";
            log.error(message, e);
            throw new AppException(message);
        }
    }

    @PostMapping("/remove")
    @RequiresPermissions("dept:delete")
    public Result deleteDepts(@NotBlank(message = "{required}") @RequestParam String deptIds) throws AppException {
        try {
            String[] ids = deptIds.split(StringPool.COMMA);
            this.deptService.deleteDepts(ids);
            return Result.ok("删除部门成功");
        } catch (Exception e) {
            message = "删除部门失败";
            log.error(message, e);
            throw new AppException(message);
        }
    }

    @PostMapping("/modify")
    @RequiresPermissions("dept:update")
    public Result updateDept(@RequestBody @Valid SysDept dept) throws AppException {
        try {
            this.deptService.updateDept(dept);
            return Result.ok("修改部门成功");
        } catch (Exception e) {
            message = "修改部门失败";
            log.error(message, e);
            throw new AppException(message);
        }
    }


}
